package com.onlinelearn.userservice.service;

import com.onlinelearn.userservice.dto.UserDTO;
import com.onlinelearn.userservice.model.User;
import com.onlinelearn.userservice.model.UserPreference;
import com.onlinelearn.userservice.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserDTO getUserById(Long id) {
        User user = userRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("用户未找到"));
        
        UserDTO userDTO = new UserDTO();
        // 转换User到UserDTO的逻辑
        return userDTO;
    }

    public void updateUserProfile(Long userId, UserDTO userDTO) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户未找到"));
        
        // 更新用户信息的逻辑
    }

    public User registerUser(User user) {
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    public User authenticateUser(String username, String password) {
        User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new UserNotFoundException("用户不存在"));
        
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new InvalidCredentialsException("密码错误");
        }
        
        return user;
    }

    public UserPreference updateUserPreferences(Long userId, UserPreference preferences) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new UserNotFoundException("用户不存在"));
        
        user.setPreferences(preferences);
        return userRepository.save(user).getPreferences();
    }
} 